package com.th.apicenter.baidu.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.th.apicenter.baidu.dto.ThBaiduNumDTO;
import com.th.apicenter.baidu.entity.ThBaiduData;
import com.th.apicenter.deduct.entity.ThDeduct;
import com.th.apicenter.kuaishou.service.KuaiShouService;
import com.th.apicenter.mapper.ThBaiduDataMapper;
import com.th.apicenter.mapper.ThDeductMapper;
import com.th.apicenter.tools.Md5Tools;
import com.th.apicenter.tools.OkhttpClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author kay
 * @date 2025/6/23
 * @TODO
 */
@Service
@Slf4j
public class BaiduService {

    @Resource
    private ThBaiduDataMapper thBaiduDataMapper;

    @Resource
    private ThDeductMapper thDeductMapper;

    @Autowired
    private KuaiShouService kuaiShouService;

    public void receive(ThBaiduData thBaiduData) {
        thBaiduDataMapper.insert(thBaiduData);
        log.info("接收到百度的数据：{}", thBaiduData);
        ThDeduct thDeduct = thDeductMapper.selectOne(new QueryWrapper<ThDeduct>()
                .eq("account_id", thBaiduData.getAccountId())
                .eq("type", "baidu"));
        if (null != thDeduct && thDeduct.getIsTrue() == 0) {
            kuaiShouService.clickBaidu(thBaiduData, thDeduct);
        }
    }

    public void callback(String actionType, String baiduId) {

        String cvType = "";
        switch (actionType) {
            case "1":
                cvType = "activate";
                break;
            case "2":
                cvType = "retain_1day";
                break;
            default:
                break;
        }
        Date currentTime = new Date();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
        String date = formatter.format(currentTime);
        String startTime = date + " 00:00:00";
        String endTime = date + " 23:59:59";

        ThBaiduData thBaiduData = thBaiduDataMapper.selectById(baiduId);
        ThDeduct thDeduct = thDeductMapper.selectOne(new QueryWrapper<ThDeduct>().eq("account_id", thBaiduData.getAccountId()).eq("type", "baidu"));
        if (null != thDeduct && !"".equals(cvType)) {

            ThBaiduNumDTO thBaiduNumDTO = thBaiduDataMapper.queryNumByDate(thBaiduData.getAccountId(), startTime, endTime);
            if (thBaiduNumDTO.getPassbackNum() >= 10) {
                BigDecimal x = new BigDecimal(thBaiduNumDTO.getPassbackNum()).divide(new BigDecimal(thBaiduNumDTO.getEffectiveNum()), 2, RoundingMode.CEILING);
                BigDecimal percent = new BigDecimal(thDeduct.getPercent()).divide(new BigDecimal(100), 2, RoundingMode.CEILING);
                if (percent.doubleValue() != 0 && new BigDecimal(1).subtract(x).compareTo(percent) < 0) {
                    log.info("需要扣量，不做操作!");
                } else {
                    String baiduResult = callbackBaidu(thBaiduData, thDeduct, actionType, cvType);
                    thBaiduData.setResultData(baiduResult);
                }
            } else {
                String baiduResult = callbackBaidu(thBaiduData, thDeduct, actionType, cvType);
                thBaiduData.setResultData(baiduResult);
            }

            if (null == thBaiduData.getKsActionType()) {
                thBaiduData.setKsActionType(actionType);
            } else if (null != thBaiduData.getKsActionType() && null == thBaiduData.getKsActionTypeO()) {
                thBaiduData.setKsActionTypeO(actionType);
            }
            thBaiduData.setUpdateTime(new Date());
            thBaiduDataMapper.updateById(thBaiduData);
        }
    }

    public String callbackBaidu(ThBaiduData thBaiduData, ThDeduct thDeduct, String actionType, String cvType) {
        String callbackUrl = thBaiduData.getCallbackUrl();
        if (null == thBaiduData.getKsActionType()) {
            thBaiduData.setKsActionType(actionType);
        } else if (null != thBaiduData.getKsActionType() && null == thBaiduData.getKsActionTypeO()) {
            thBaiduData.setKsActionTypeO(actionType);
        }
        callbackUrl = callbackUrl.replace("{{ATYPE}}", cvType).replace("{{AVALUE}}", "0") + "&akey=" + thDeduct.getVivoToken();
        String sign = Md5Tools.md5(callbackUrl);
        callbackUrl = callbackUrl + "&join_type=oaid" + "&sign=" + sign;
        String baiduResult = OkhttpClient.httpGet(callbackUrl);
        return baiduResult;
    }
}
